<script setup>
import {
  GetListAPI,
  AddDataAPI,
  DelDataAPI,
  GetViewAPI,
  ReturnConfirmAPI,
  EditDataAPI,
  GetReturnListAPI,
} from '@/api/mold/scrap'

import SubmitForm from './submitForm.vue'
import useDic from './use.vue'
const { proxy } = getCurrentInstance()

/**
 * 字典查询
 */
const { sys_scrap_management } = proxy.useDict('sys_scrap_management')

/**
 * 模糊查询枚举
 */
const selectList = ref([
  { type: '日期范围' },
  { label: '刀具名称', model: 'mouldName', type: '输入框' },
  { label: '刀具类型', model: 'mouldType', type: '刀具类型' },
  // { label: '安装地点', model: 'installationSite', type: '输入框' },
])
/**
 * 表单实例
 */
const ruleFormRef = ref(null)
/**
 * 表单
 */
const ruleForm = ref({})
/**
 * 表格枚举
 */
const columns = ref([
  { label: '报废单号', prop: 'scrapCode' },
  { label: '模具名称', prop: 'mouldName' },
  { label: '模具编码', prop: 'mouldCode' },
  { label: '模具类型', prop: 'mouldType' },
  { label: '制造厂商', prop: 'factoryName' },
  { label: '状态', prop: 'status' },
  { label: '备注', prop: 'remark' },
  { label: '报废人', prop: 'scrapName' },
  { label: '创建时间', prop: 'createTime' },
  { label: '报废时间', prop: 'scrapTime' },
  { label: '确认人', prop: 'verifyBy' },
  { label: '操作', prop: 'x' },
])
/**
 * 各种状态
 */
const state = reactive({
  loading: false,
  total: 0,
  btnLoading: false,
  isShow: false,
  title: '新增',
  row: [],
  ids: [],
  treeShow: false, //树结构弹窗
  use: false, //领用弹窗
  usedis: true,
  tableData: [],
})

const usedis = ref(true)
/**
 * 按钮枚举
 */
const buttonList = ref([
  { type: 'add', hasPermi: 'mold:scrap:add' },
  {
    label: '报废确认',
    type: '自定义',
    hasPermi: 'mold:scrap:scrapAdd',
    emit: 'useAddDic',
    disabled: usedis,
  },
])

/**
 * 表格数据
 */
const tableData = ref([])

/**
 * 表单实例
 */
const submitFormRef = ref(null)

/**
 * 新增修改表单
 */
const submitForm = ref({})

/**
 * 查询表单
 */
const query = reactive({
  pageNum: 1,
  pageSize: 10,
})

/**
 * 表单校验
 */
const rules = reactive({
  type: [{ required: true, message: '请选择设备类型', trigger: 'change' }],
})

/**
 * 新增弹窗
 */
const addDic = () => {
  state.title = '新增'
  state.isShow = true
}

/**
 * 修改弹窗
 */
const editDic = async (id) => {
  try {
    state.btnLoading = true
    const { data: result } = await GetViewAPI(id)
    submitForm.value = result
    state.title = '修改'
    state.isShow = true
  } catch (err) {
    console.error(err)
  } finally {
    state.btnLoading = false
  }
}

/**
 * 查看弹窗
 */
const lookDic = async (id) => {
  try {
    state.btnLoading = true
    const { data: result } = await GetViewAPI(id)
    submitForm.value = result
    state.title = '查看'
    state.isShow = true3
  } catch (err) {
    console.error(err)
  } finally {
    state.btnLoading = false
  }
}

/**
 * 弹窗关闭
 */
const closeDic = () => {
  state.isShow = false
  state.use = false
  submitForm.value = {}
}

/**
 * 新增
 */
const addSub = async () => {
  try {
    state.btnLoading = true
    const result = await submitFormRef.value.submit()
    if (!result) return
    await AddDataAPI(result)
    closeDic()
    proxy.successMsg('新增成功')
    getList()
  } catch (err) {
    console.error(err)
  } finally {
    state.btnLoading = false
  }
}

/**
 * 修改
 */
const editSub = async () => {
  try {
    state.btnLoading = true
    const result = await submitFormRef.value.submit()
    await EditDataAPI(result)
    closeDic()
    proxy.successMsg('修改成功')
    getList()
  } catch (err) {
    console.error(err)
  } finally {
    state.btnLoading = false
  }
}

/**
 * 修改状态
 */
const changeStatus = async (val) => {
  const result = await proxy.MessageBox(
    `是否修改状态为${val.status == 0 ? '不启用' : '启用'}?`
  )
  if (!result) {
    val.status == 1 ? (val.status = 0) : (val.status = 1)
    return
  }
  try {
    // await UpdateStatusAPI({
    //   id: val.id,
    //   status: val.status,
    // });
    proxy.successMsg('修改成功!')
    // getList();
  } catch {
    val.status == 1 ? (val.status = 0) : (val.status = 1)
  } finally {
  }
}

/**
 * 删除
 */
const remove = async (id) => {
  try {
    proxy.loading('删除中，请稍后')
    await DelDataAPI(id)
    closeDic()
    proxy.successMsg('删除成功')
    getList()
  } catch (err) {
    console.error(err)
  } finally {
    proxy.closeLoading()
  }
}

/**
 * 模糊查询
 */
const selectSubmit = (val) => {
  Object.keys(val).forEach((keyItem) => (query[keyItem] = val[keyItem]))
  getList()
}

/**
 * 列表复选框
 */
const handleSelectionChange = ({ row, ids }) => {
  state.ids = ids
  state.row = row
  usedis.value = state.row.length > 0 ? false : true
}

/**
 * 领用弹窗
 */

const useAddDic = async () => {
  try {
    const { data: result } = await GetReturnListAPI({ idList: state.ids })
    state.tableData = result
    state.use = true
  } catch (err) {
    console.error(err)
  } finally {
  }
}

/**
 * 退回确认
 */
const useSub = async () => {
  try {
    state.btnLoading = true
    const result = await submitFormRef.value.submit()
    if (!result) return
    await ReturnConfirmAPI({ scrapList: result })
    closeDic()
    proxy.successMsg('报废确认成功')
    getList()
  } catch (err) {
    console.error(err)
  } finally {
    state.btnLoading = false
  }
}

/**
 * 查询列表
 */
const getList = async () => {
  try {
    state.loading = true
    const result = await GetListAPI(query)
    state.total = result.total
    tableData.value = result.rows
  } catch (err) {
    console.error(err)
  } finally {
    state.loading = false
  }
}
getList()
</script>

<template>
  <div class="app-container">
    <!-- 查询条件组件 -->
    <p-select-form :selectForm="selectList" @selectSubmit="selectSubmit" />

    <el-card>
      <!-- 表格数据 -->
      <p-table
        class="tableClass"
        :loading="state.loading"
        :data="tableData"
        :column="columns"
        v-model:page="query.pageNum"
        v-model:limit="query.pageSize"
        :total="state.total"
        @change="handleSelectionChange"
        @pagination="getList"
      >
        <template #buttons>
          <p-button :list="buttonList" @add="addDic" @useAddDic="useAddDic"
        /></template>
        <template #columnCell="{ column, record }">
          <p-dictTag
            v-if="column.prop == 'status'"
            :options="sys_scrap_management"
            :value="record.status"
          />
          <p-operate
            :list="[
              {
                icon: 'Edit',
                emit: 'edit',
                disabled: record.status == 2,
                text: '修改',
                type: 'primary',
                hasPermi: 'mold:scrap:edit',
              },
              {
                icon: 'DeleteFilled',
                emit: 'remove',
                disabled: record.status == 2,
                text: '删除',
                isDel: true,
                type: 'danger',
                hasPermi: 'mold:scrap:remove',
              },
            ]"
            v-if="column.prop == 'x'"
            @look="lookDic(record.id)"
            @edit="editDic(record.id)"
            @remove="remove(record.id)"
          />
        </template>
      </p-table>
    </el-card>

    <!-- 弹窗 新增-修改 -->
    <p-dialog
      v-model="state.isShow"
      :title="state.title"
      @ok="state.title == '新增' ? addSub() : editSub()"
      @close="closeDic"
      width="60%"
    >
      <SubmitForm
        ref="submitFormRef"
        :data="submitForm"
        :title="state.title"
        :disabled="state.title == '查看'"
      />
    </p-dialog>
    <!-- 领用确认 -->
    <p-dialog
      v-model="state.use"
      :title="'报废确认'"
      @ok="useSub()"
      @close="closeDic"
      width="60%"
    >
      <useDic ref="submitFormRef" :data="state.tableData" />
    </p-dialog>
  </div>
</template>

<style scoped lang="scss">
.card-tree {
  height: 30rem;
  overflow: auto;
}
.card-header {
  display: flex;
  justify-content: space-between;
}
</style>
